package com.epam.employeebase.dao.hibernate;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Order;

import com.epam.employeebase.dao.IEmployeeDAO;
import com.epam.employeebase.dao.exception.DAOException;
import com.epam.employeebase.entity.Employee;
import com.epam.employeebase.util.HibernateUtil;

public final class HibernateEmployeeDAO implements IEmployeeDAO{
	private static final String EMPLOYEE_COUNT_QUERY_NAME = "employee count";
	private static final String EMPLOYEE_ID_COLUMN_NAME = "id";

	@Override
	public List<Employee> list(int firstEntry, int entriesNumber) throws DAOException {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		
		session.beginTransaction();
		Criteria criteria = session.createCriteria(Employee.class);
		@SuppressWarnings("unchecked")
		List<Employee> employeeList = criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY)
										.setFirstResult(firstEntry).setMaxResults(entriesNumber)
										.addOrder(Order.asc(EMPLOYEE_ID_COLUMN_NAME)).list();
		session.getTransaction().commit();
		return employeeList;
	}

	@Override
	public long employeeCount() throws DAOException {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();		
		session.beginTransaction();
		Query query = session.getNamedQuery(EMPLOYEE_COUNT_QUERY_NAME);
		long employeeCount = (long) query.uniqueResult();
		session.getTransaction().commit();
		return employeeCount;
	}

}
